﻿using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NP.BPMReportPlatform.Contract.Dtos;
using NP.BPMReportPlatform.ElectronicSign.Dto;
using NP.BPMReportPlatform.Entities.BPM_Business.Contract;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.Reports.OrderMaterialDetail.Dtos;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.Contract
{
    /// <summary>
    /// 合同接口
    /// </summary>
    //[Authorize]
    [ApiController]
    [Route("api/contract")]
    public class ContractController : BPMReportPlatformController
    {
        private readonly IContractService _contractService;
        private readonly ISFSyncJob _sfSyncJob;
        private readonly IExcelImporter _importer;

        public ContractController(IContractService contractService, ISFSyncJob sfSyncJob, IExcelImporter importer)
        {
            _contractService = contractService;
            _sfSyncJob = sfSyncJob;
            _importer = importer;
        }

        /// <summary>
        /// 根据条件合同订立
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractFormation/getContractUserFormationList")]
        public Task<PagedResultDto<ContractUserListDto>> GetContractUserFormationList([FromQuery] SearchQueryDto searchQuery)
        {
            if (searchQuery.ExcelType == 6)
            {
                return _contractService.GetIntelContractUserFormationList(searchQuery);
            }
            else if (searchQuery.ExcelType == 7)
            {
                return _contractService.GetRetirementContractUserFormationList(searchQuery);
            }

            return _contractService.GetContractUserFormationList(searchQuery);
        }

        /// <summary>
        /// 根据人员主键ID初始化订立合同基本信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractFormation/package-user-contract-info")]
        public UserContractEntity PackageUserContractInfo(string userId)
        {
            return _contractService.PackageUserContractInfo(userId);
        }

        /// <summary>
        /// 根据人员主键ID初始化订立合同基本信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractFormation/get-formation-contract-info")]
        public UserContractEntity GetFormationContract(string userId)
        {
            return _contractService.PackageUserContractInfo(userId, true);
        }

        /// <summary>
        /// 根据数据获取当前合同编码
        /// </summary>
        /// <param name="contractType">合同类型</param>
        /// <param name="contractStartDate">合同开始时间</param>
        /// <param name="workNumber">员工编码</param>
        /// <param name="parentContractCode">原始合同：上一份合同</param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractFormation/generate-contract-code")]
        public string GenerateContractCode([FromQuery] string contractType, [FromQuery] string contractStartDate, [FromQuery] string workNumber, [FromQuery] string parentContractCode)
        {
            return _contractService.GenerateContractCode(contractType, contractStartDate, workNumber, parentContractCode);
        }

        /// <summary>
        /// 保存合同订立--立即生效
        /// </summary>
        /// <param name="entity">数据</param>
        [HttpPost]
        [Route("contractFormation/save-contract")]
        public Task<string> SaveUserContract([FromBody] UserContractEntity entity)
        {
            return _contractService.SaveUserContract(entity, 1);
        }

        /// <summary>
        /// 保存合同订立--电子签
        /// </summary>
        /// <param name="entity">数据</param>
        [HttpPost]
        [Route("contractFormation/save-contract-for-electronic")]
        public Task<string> SaveUserContractForElectronic([FromBody] UserContractEntity entity)
        {
            return _contractService.SaveUserContract(entity, 2);
        }

        /// <summary>
        /// 根据条件
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractRenewal/get-renewal-list")]
        public Task<PagedResultDto<ContractUserListDto>> GetContractUserRenewalList([FromQuery] SearchQueryDto searchQuery)
        {
            return _contractService.GetContractUserRenewalList(searchQuery);
        }

        /// <summary>
        /// 根据人员工号获取续订合同信息
        /// </summary>
        /// <param name="workNumber"></param>
        /// <param name="parentContractCode">上一份合同</param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractRenewal/search-user-contract")]
        public ContractRenewalDto SearchUserContract(string workNumber, string parentContractCode)
        {
            return _contractService.SearchUserContract(workNumber, parentContractCode);
        }

        /// <summary>
        /// 下载合同
        /// </summary>
        /// <param name="processId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("download-contract")]
        public async Task<string> DownloadContract([FromQuery] string processId)
        {
            return await _contractService.DownloadContract(processId);
        }

        /// <summary>
        /// 流程任务 type:1 催办 2 作废
        /// </summary>
        /// <param name="type"></param>
        /// <param name="contractCode">合同编码</param>
        [HttpGet]
        [Route("process-task")]
        public async Task<string> ProcessTask([FromQuery] int type, [FromQuery] string contractCode)
        {
            return await _contractService.ProcessTask(type, contractCode);
        }

        /// <summary>
        /// 三方协议流程任务 type:1 催办 2 作废
        /// </summary>
        /// <param name="type"></param>
        /// <param name="changeContractCode">合同编码</param>
        [HttpGet]
        [Route("process-change-task")]
        public async Task<string> ProcessChangeTask([FromQuery] int type, [FromQuery] string changeContractCode)
        {
            return await _contractService.ProcessChangeTask(type, changeContractCode);
        }

        /// <summary>
        /// 根据合同编码获取合同基本信息
        /// </summary>
        /// <param name="contractCode">合同编码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("get-contract-info")]
        public UserContractEntity GetUserContractInfo([FromQuery] string contractCode)
        {
            return _contractService.GetUserContractInfo(contractCode);
        }

        /// <summary>
        /// 导出对应列表数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("exportAsync")]
        public async Task<FileResult> ExportResultAsync([FromBody] SearchQueryDto search)
        {
            var rst = await _contractService.ExportResultAsync(search);
            string downloadFileName = System.Guid.NewGuid().ToString("N") + ".xlsx";
            rst.Close();
            return File(rst.ToArray(), "application/octet-stream", $"{downloadFileName}.xlsx");
        }

        /// <summary>
        /// 合同三方协议变更
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractChange/get-change-list")]
        public Task<PagedResultDto<ContractUserListDto>> GetAllTripartiteContract([FromQuery] SearchQueryDto searchQuery)
        {
            return _contractService.GetAllTripartiteContract(searchQuery);
        }

        /// <summary>
        /// 根据条件查询--合同主体变更三方协议记录查询
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractChange/get-change-history-list")]
        public Task<PagedResultDto<ContractUserListDto>> GetTripartiteHistoryList([FromQuery] SearchQueryDto searchQuery)
        {
            return _contractService.GetTripartiteHistoryList(searchQuery);
        }

        /// <summary>
        /// 生成变更合同协议编码
        /// </summary>
        /// <param name="workNumber">员工编码</param>
        /// <param name="contractCode">合同编码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractChange/generate-change-contract")]
        public UserContractTripartiteAgreementEntity GenerateChangeContractCode([FromQuery] string workNumber, [FromQuery] string contractCode)
        {
            return _contractService.GenerateChangeContract(workNumber, contractCode);
        }

        /// <summary>
        /// 保存变更合同--立即生效
        /// </summary>
        /// <param name="entity">数据</param>
        [HttpPost]
        [Route("contractChange/save-contract")]
        public Task<string> SaveUserChangeContract([FromBody] UserContractTripartiteAgreementEntity entity)
        {
            return _contractService.SaveUserChangeContract(entity, 1);
        }

        /// <summary>
        /// 保存变更合同--电子签
        /// </summary>
        /// <param name="entity">数据</param>
        [HttpPost]
        [Route("contractChange/save-contract-for-electronic")]
        public Task<string> SaveUserChangeContractForElectronic([FromBody] UserContractTripartiteAgreementEntity entity)
        {
            return _contractService.SaveUserChangeContract(entity, 2);
        }

        /// <summary>
        /// 根据查询条件查询-合同续签审批报表
        /// </summary>
        /// <param name="searchQuery">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        [Route("get-renewal-process-report")]
        public Task<PagedResultDto<UserContractRenewalProcessEntity>> GetContractRenewalProcessByFilter([FromQuery] SearchQueryDto searchQuery)
        {
            return _contractService.GetContractRenewalProcessByFilter(searchQuery);
        }

        /// <summary>
        /// 获取新员工
        /// </summary>
        /// <param name="workNumber"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("contractFormation/get-new-staff")]
        public async Task<object> GetNewStaff([FromQuery] string workNumber)
        {
            // return await _sfSyncJob.SyncHanaUserAsync(workNumber);
            return _contractService.GetNewStaff(workNumber);
        }

        /// <summary>
        /// 电子签推送失败重推
        /// </summary>
        /// <param name="contractId">合同ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("ReRequestESignSyncData")]
        public async Task<object> ReRequestESignSyncData([FromQuery] string contractId)
        {
            return await _contractService.ReRequestESignSyncData(contractId);
        }

        /// <summary>
        /// 测试合同模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("TestContractTemplate")]
        public async Task<FileResult> TestContractTemplate([FromBody] UserContractEntity entity)
        {
            var rst = await _contractService.TestContractTemplate(entity);
            return File(rst, "application/octet-stream", $"{Guid.NewGuid()}.pdf");
        }
        /// <summary>
        /// 手动推送合同信息到SF
        /// </summary>
        /// <param name="contractCode"></param>
        /// <returns></returns>
        [HttpPost("PushContractToSF")]
        public string PushContractToSF(string contractCode)
        {
            return _sfSyncJob.PushContractToSF(contractCode);
        }

        /// <summary>
        /// 导入主体变更协议
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ImportTripartiteAgreementContracts")]
        public async Task<ImportResultExt<TripartiteAgreementContractImportDto>> ImportTripartiteAgreementContracts(IFormFile file)
        {
            if (file == null)
            {
                var res = new ImportResultExt<TripartiteAgreementContractImportDto>
                {
                    Exception = new Exception("请上传文件！")
                };
                return res;
            }
            var stream = file.OpenReadStream();
            var rst = await _importer.Import<TripartiteAgreementContractImportDto>(stream);
            stream.Close();
            if (rst.HasError)
            {
                var resp = new ImportResultExt<TripartiteAgreementContractImportDto>()
                {
                    Exception = rst.Exception,
                    RowErrors = rst.RowErrors,
                    TemplateErrors = rst.TemplateErrors
                };
                return resp;
            }
            else
            {
                return await _contractService.ImportTripartiteAgreementContracts(rst.Data.ToList());
            }
        }

        /// <summary>
        /// 导出主体变更协议导入模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("ExportTripartiteAgreementContractTemplate")]
        public async Task<XlsxFileResult<TripartiteAgreementContractImportDto>> ExportTripartiteAgreementContractTemplate()
        {
            var rst = new List<TripartiteAgreementContractImportDto>();
            return new XlsxFileResult<TripartiteAgreementContractImportDto>(rst, "主体变更协议导入模板.xlsx");
        }
    }
}
